package com.version1.test.service;

import com.version1.test.entity.ComparisonList;
import com.version1.test.entity.InsuranceRecord;
import com.version1.test.entity.VillageCadre;
import com.version1.test.entity.VillageEnterprise;
import com.version1.test.mapper.ComparisonListMapper;
import com.version1.test.mapper.InsuranceRecordMapper;
import com.version1.test.mapper.VillageCadreMapper;
import com.version1.test.mapper.VillageEnterpriseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class ComparisonService {

    @Autowired
    private InsuranceRecordMapper insuranceRecordMapper;

    @Autowired
    private VillageCadreMapper villageCadreMapper;

    @Autowired
    private ComparisonListMapper comparisonListMapper;

    @Autowired
    private VillageEnterpriseMapper villageEnterpriseMapper;

    public void generateComparisonList() {
        List<InsuranceRecord> insuranceRecords = insuranceRecordMapper.selectAll();
        List<VillageCadre> villageCadres = villageCadreMapper.selectAll();
        Map<String, VillageCadre> villageCadreMap = new HashMap<>();
        for (VillageCadre vc : villageCadres) {
            villageCadreMap.put(vc.getIdcard(), vc);
        }

        for (InsuranceRecord ir : insuranceRecords) {
            VillageCadre vc = villageCadreMap.get(ir.getIdcard());
            if (vc != null && ir.getInsuranceYearMonth().equals(vc.getAppointmentTime())) {
                ComparisonList existing = comparisonListMapper.selectByIdNumber(ir.getIdcard());
                if (existing == null) {
                    ComparisonList cl = new ComparisonList();
                    cl.setName(ir.getName());
                    cl.setIdNumber(ir.getIdcard());
                    cl.setCurrentPosition(vc.getCurrentPosition());
                    cl.setAffiliatedTown(vc.getAffiliatedTown());
                    cl.setInsuranceYearMonth(ir.getInsuranceYearMonth());
                    cl.setPaymentUnit(ir.getPaymentUnit());
                    comparisonListMapper.insert(cl);
                }
            }
        }
        System.out.println("对比名单生成完成。");
    }

    public List<ComparisonList> generateAlerts() {
        List<ComparisonList> comparisonLists = comparisonListMapper.selectAll();
        List<VillageEnterprise> villageEnterprises = villageEnterpriseMapper.selectAll();
        Set<String> enterpriseNames = new HashSet<>();
        for (VillageEnterprise ve : villageEnterprises) {
            enterpriseNames.add(ve.getEnterpriseName());
        }

        List<ComparisonList> alerts = new ArrayList<>();
        for (ComparisonList cl : comparisonLists) {
            if (enterpriseNames.contains(cl.getPaymentUnit())) {
                alerts.add(cl);
            }
        }
        return alerts;
    }
}